<!-- ***************************************************************************
* Copyright (c) 2013 IBM Corp.
* Copyright 2017 Huawei Technologies Co., Ltd
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
*    http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
**************************************************************************** -->
<!-- this sourcecode is modified by Huawei Technologies Co., Ltd. -->
<!DOCTYPE HTML>
<html>

<head>
  <title>Huawei Air - Check In</title>
  <meta http-equiv="content-type" content="text/html; charset=UTF-8" />
  <link rel="stylesheet" type="text/css" href="css/style.css">
  <link rel="stylesheet" href="css/themes/claro/claro.css">
  <link rel="stylesheet" href="css/themes/claro/claroGrid.css">

  <script type="text/javascript" src="js/acmeair-common.js"></script>
  <script src="https://download.dojotoolkit.org/release-1.7.12/dojo-release-1.7.12/dojo/dojo.js" djConfig="parseOnLoad: true"></script>

		<script>
			dojo.require("dojo.cookie");
			dojo.require("dojox.grid.DataGrid");
			dojo.require("dojo.data.ItemFileWriteStore");
			// TODO:  included this to get the date formatting support, is there a better way?
			dojo.require("dijit.form.DateTextBox");
			dojo.require("dijit.Dialog");
			dojo.require("dijit.Toolbar");
			dojo.require("dijit.Declaration");
			dojo.require("dojo.currency");
			
			dojo.addOnLoad(pageLoaded);
			
		    function pageLoaded() {
		    	updateLoggedInUserWelcome();
		    	createAndStartGrid();
		    }
		    
		    function createAndStartGrid() {
		    	var grid, store, dataStore;
		    	var xhrContent = {userId: dojo.cookie("loggedinuser")};
		    	dojo.xhrGet({
					//url: "bookings/rest/api/bookings/byuser/" + dojo.cookie("loggedinuser"),
					url: "orders/huaweiair/v1/orders",
					content: xhrContent,
					handleAs: "json",
					load: function(response, ioArgs) {
						var theData = { items : response };
						var newStore = new dojo.data.ItemFileWriteStore({
							data : theData
						});
						var flightsGrid = dijit.byId("gridFlights");
						try {
							flightsGrid.setStore(newStore);
							flightsGrid.update();
						} catch(err) {
							console.log(err);
						}
						console.log(dojo.currency.format(200, {currency: "USD"}));
					},
					error: function(response, ioArgs) {
						alert("Load orders failure.\n" + response);
					}
		    	});
		    }
		    
		    
			
			function formatFlightNumnber(data) {
				// TODO:  Why [0]?? Also, why can't I just put this path into the declarative table markup?
				return data.flightSegmentId[0];
			}
			
			function returnIfNotLoggedIn() {
				var loggedinuser = dojo.cookie("loggedinuser");
				if (loggedinuser == null) {
					alert("you need to login first before selecting flights");
					return true;
				}
				return false;
			}

			function cellclick(e) {
				if (returnIfNotLoggedIn()) { return }
				
				var gridId = e.grid.id;
				var selectedIndex = getCurrentlySelectedIndexForGrid(gridId);
				
				var grid = dijit.byId(gridId);
				
				if (grid.getItem(e.rowIndex).selected && grid.getItem(e.rowIndex).selected == "selected") {
					grid.getItem(e.rowIndex).selected = '...';
					if (e.rowIndex == selectedIndex) {
						selectedIndex = -1;
					}
				}
				else {
					grid.getItem(e.rowIndex).selected = 'selected';
					selectedIndex = e.rowIndex; 
				}
				
				setCurrentlySelectedIndexForGrid(gridId, selectedIndex);
				
				var store = grid.store;
				store.close();
				grid.setStore(store);
			}
			
			function getCurrentlySelectedIndexForGrid(gridId) {
				if (gridId == 'gridFlights') {
					return selectedIndexForFlights;
				}
				else {
					console.error("wrong grid specified");
				}
			}
			
			function setCurrentlySelectedIndexForGrid(gridId, value) {
				if (gridId == 'gridFlights') {
					selectedIndexForFlights = value;
				}				
				else {
					console.error("wrong grid specified");
				}
			}
			
			function formatSelected(data) {
				// TODO:  not sure why setting the value results in only one character, but trying to make progress
				// I see the data value in alert either being "s" or ".", the first character of the entire string I set
				if (data && (data == "selected" || data == 's')) {
					return "selected";
				}
				else {
					return "select ...";
				}
			}

			function updateOrderStatus(checkCallback, updateStatus) {
				if (returnIfNotLoggedIn()) { return }

				var loggedinuser = dojo.cookie("loggedinuser");
				
				if (selectedIndexForFlights == -1) {
					alert("please select a order");
					return;
				}
				var grid = dijit.byId("gridFlights");
				var orderId = grid.store.getValue(grid.getItem(selectedIndexForFlights), "orderId");
				var orderStatus = grid.store.getValue(grid.getItem(selectedIndexForFlights), "orderStatus");
				orderStatus = orderStatusDesc2Int(orderStatus);
				var error = checkCallback(orderStatus);
				if ( error != null) {
					alert(error);
					return;
				}
				var xhrAgrs = {
					url: 'orders/huaweiair/v1/orders/' + orderId,
					content: {action: updateStatus},
					handleAs: 'json',
					load: function(response, ioArgs){
						if (updateStatus == ORDER_STATUS_VALID) {
							alert("Pay order " + orderId + " succeed.")
						} else if (updateStatus == ORDER_STATUS_CANCELED) {
							alert("Cancel order " + orderId + " succeed.")
						} else {
							alert("Update order " + orderId + " to status " + updateStatus + " succeed.")
						}
						
						createAndStartGrid();
					},
					error: function(response, ioArgs){
						if (updateStatus == ORDER_STATUS_VALID) {
							alert("Pay order " + orderId + " failure.\n" + response)
						} else if (updateStatus == ORDER_STATUS_CANCELED) {
							alert("Cancel order " + orderId + " failure.\n" + response)
						} else {
							alert("Update order " + orderId + " to status " + updateStatus + " failure.\n" + response)
						}
					}
				};
				var defered = dojo.xhrPut(xhrAgrs);
			}

			function payOrder() {
				var check = function(status){
					if (status != ORDER_STATUS_WAITTING_PAYMENT) {
						return "Only 'Waitting Payment' orders allow to pay.";
					}
					return null;
				};
				updateOrderStatus(check, ORDER_STATUS_VALID);
			}

			function cancelOrder() {
				var check = function(status){
					if (status == ORDER_STATUS_USED) {
						return "Order already used, not allowed to cancel any more.";
					}
					if (status == ORDER_STATUS_CANCELED) {
						return "Order already canceled."
					}
					return null;
				};
				updateOrderStatus(check, ORDER_STATUS_CANCELED);
			}

			function deleteOrder() {
				if (returnIfNotLoggedIn()) { return }

				var loggedinuser = dojo.cookie("loggedinuser");
				
				if (selectedIndexForFlights == -1) {
					alert("please select a order");
					return;
				}
				var grid = dijit.byId("gridFlights");
				var orderId = grid.store.getValue(grid.getItem(selectedIndexForFlights), "orderId");				
				var xhrAgrs = {
					url: 'orders/huaweiair/v1/orders/' + orderId,
					load: function(response, ioArgs){
						alert("delete order " + orderId + " succeed.")
						createAndStartGrid();
					},
					error: function(response, ioArgs){
						alert("delete order " + orderId + " failure.\n" + response);
					}
				};
				var defered = dojo.xhrDelete(xhrAgrs);
			}
			
			var selectedIndexForFlights = -1;
		</script>
</head>

<body class="claro">
<span id="variousDialogs" style="display:none">
<div dojoType="dijit.Dialog" id="loginWaitDialog" title="Please Wait">
		<table width="258">
			<tr><td>Logging in ...</td></tr>
		</table>
</div>

<div dojoType="dijit.Dialog" id="loginDialog" title="Login">
		<table width="258">
			<tr>
				<td><label>Login</label></td>
				<td><input type="text" trim="true" dojoType="dijit.form.TextBox" value="uid0@email.com" name="login" id="userId"/></td>
			</tr>
			<tr>
				<td><label>Password</label></td>
				<td><input type="password" trim="true" dojoType="dijit.form.TextBox" value="password" name="password" id="password"/></td>
			</tr>
			<tr>
				<td colspan="2">&nbsp;</td>
			</tr>
			<tr>
				<td colspan="2" align="center">
					<table width="100%" border="0" cellspacing="0" cellpadding="0">
						<tr>
							<td  align="center" valign="top" width="40%"><button dojoType="dijit.form.Button" id="LoginButton" onClick="login()">Ok</button></td>
							<td align="left" valign="top" width="3%">&nbsp;</td>
							<td align="left" valign="top" width="57%"><button dojoType="dijit.form.Button" onclick="hideLoginDialog()" id="Cancel">Cancel</button></td>
						</tr>
					</table>
				</td>
			</tr>
		</table>
</div>
</span>
  <div id="main">
	<br/>
	<header>
		<br/><br/><br/>
		<img src="images/Huawei Air.png" alt="Huawei Air"/><br/><br/>
		<div class="text-align: left">Our commitment, your pursuit.</div><br/>
	</header>
	<div id="welcomeback"><div id="loggedinwelcome"></div>
	</div>
	<div id="main_content">
		<span data-dojo-type="dijit.Declaration" data-dojo-props='widgetClass:"ToolbarSectionStart", defaults:{ label: "Label"}'>
			<span data-dojo-type="dijit.ToolbarSeparator"></span><i>${label}:</i>
		</span>

		<div id="toolbar5" data-dojo-type="dijit.Toolbar">
			<div data-dojo-type="ToolbarSectionStart" data-dojo-props='label:"Actions"'></div>
			<div id="toolbar5.home" data-dojo-type="dijit.form.Button" data-dojo-props='showLabel:true' onClick="window.location='index.html'">Home</div>
			<div id="toolbar5.flights" data-dojo-type="dijit.form.Button" data-dojo-props='showLabel:true' onClick="window.location='flights.html'">Flights</div>
			<div id="toolbar5.order" data-dojo-type="dijit.form.Button" data-dojo-props='showLabel:true' onClick="window.location='orders.html'">Orders</div>
			<div id="toolbar5.login" data-dojo-type="dijit.form.Button" data-dojo-props='showLabel:true' onClick="showLoginDialog()">Login</div>
			<div id="toolbar5.logout" data-dojo-type="dijit.form.Button" data-dojo-props='showLabel:true' onClick="logout()">Logout</div>
			<div id="toolbar5.account" data-dojo-type="dijit.form.Button" data-dojo-props='showLabel:true' onClick="window.location='customerprofile.html'">Account</div>
		</div>
		
		<div class="content">
		<table data-dojo-type="dojox.grid.DataGrid" id="gridFlights" style="height: 400px">
			<script type="dojo/connect" event="onCellClick" args="e">cellclick(e)</script> 
  	        	<thead>
     	        	<tr>
						<span field="orderId" style="visibility:hidden;"></span>
						<th field="name" width="80px">Order Name</th>
						<th field="orderTime" width="100px">Order Time</th>
						<th field="orderStatus" formatter="orderStatusFormatter" width="70px">Order Status</th>
						<th field="flightId" width="100px">Flight</th>
						<th field="scheduledDepartureTime" width="80px">Daparture Time</th>
						<th field="scheduledArrivalTime" width="80px">Arrival Time</th>
						<th field="flightClass" formatter="flightClassFormatter" width="70px">Flight Class</th>
						<th field="flightPrice" formatter="currencyFormatter" width="80px">Amount</th>
						<th field="selected" formatter="formatSelected" width="120px" value="Select">Select</th>
					</tr>
				</thead>
		</table>
		<button dojoType="dijit.form.Button" id="payOrder" onClick="payOrder()">Pay</button>
		<button dojoType="dijit.form.Button" id="cancelOrder" onClick="cancelOrder()">Cancel</button>
		<button dojoType="dijit.form.Button" id="deleteOrder" onClick="deleteOrder()">Delete</button>
		</div>
	</div>
	<footer>
		<p><a href="config.html">configure the Huawei Air environment.</a></p>
	</footer>

</div>

<p>&nbsp;</p>
</body>
</html>
